package com.hcms.base.controller;

import com.hcms.common.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {

    String prefix = "base/login/";

    @RequestMapping("/")
    public String index() {
        return prefix + "index";
    }

    // 提交登录
    @PostMapping("/dologin")
    @ResponseBody
    public Result doLogin(String username, String password, boolean isRememberMe) {
        // 1、获取 Subject 对象
        Subject subject = SecurityUtils.getSubject();

        // 2、通过 Subject 提交用户信息，交给 shiro 框架进行认证操作

        // 2.1、 创建一个身份验证令牌
        UsernamePasswordToken token = new UsernamePasswordToken(
                username,   // 身份信息
                password,   // 凭证信息
                isRememberMe    // 记住登录状态
        );

        try {
            // 2.2、 对用户进行身份认证
            subject.login(token);

            // 2.3、身份验证成功，执行其它逻辑

        } catch (UnknownAccountException e) {
            // 2.4、账号不存在，处理异常
            return Result.error(-1, e.getMessage());
        } catch (CredentialsException e) {
            // 2.5、密码不正确，处理异常
            return Result.error(-1, "密码不正确");
        }

        return Result.ok();
    }

    // 注销登录
    @GetMapping("/logout")
    public String logout(HttpServletResponse response, HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            session.invalidate();
            subject.logout();
            Cookie cookie = new Cookie("rememberMe", null);
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            response.addCookie(cookie);
        }

        return "redirect:/login/";  // 重定向到 登录页
    }
}
